<?php
/**
 * Save user's javascript code
 */

require_once(dirname(__FILE__) . "/start.inc");
global $CONFIG;

$vid = getVar('vid');
$name = getVar('name');
$url = getVar('url');
$content = getVar('content');

$output = array();
$output['result'] = false;
if (isloggedin()) {
    if ($name && $url && $content) {
        if (isset($_SESSION['CV'])) {
            $codeVersion = $_SESSION['CV'];
	        $content = $codeVersion->content.$content;
        } elseif ($vid) {
	        $codeVersion = new CodeVersion($vid);
	        $content = $codeVersion->content.$content;
        } else {
            $codeVersion = new CodeVersion();
        }

	    error_log('-------->'.$content);

        $codeVersion->name = $name.mt_rand(0, 10000); // TODO, demo code
        $codeVersion->url = $url;
        $codeVersion->content = $content;

        if ($codeVersion->save()) {
            $_SESSION['CV'] = $codeVersion;
            $output['result'] = true;
        } else {
            $output['message'] = 'save code fail';
            $output['error'] = 2;
        }
    } else {
        $output['message'] = 'Bad parameters';
        $output['error'] = 1;
    }
} else {
    $output['message'] = 'Please login first';
    $output['error'] = 0; // not login
}

echo json_encode($output);
exit;